package com.fatmeraid.controller.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AbstractAlipayClient;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.fatmeraid.common.exception.FarmException;
import com.fatmeraid.common.result.ResultCodeEnum;
import com.fatmeraid.custom.config.AliPayConfig;
import com.fatmeraid.domain.Order;
import com.fatmeraid.service.OrderService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "支付管理")
@Controller
@RequestMapping("/alipay")
public class AliPayController {
    // 支付宝沙箱网关地址
	private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
	private static final String FORMAT = "JSON";
	private static final String CHARSET = "utf-8";
	// 签名方式
	private static final String SIGN_TYPE = "RSA2";

	@Autowired
	private AliPayConfig aliPayConfig;

	@Autowired
	private OrderService orderService;


	@RequestMapping("/pay")
	public void pay(Long orderId, HttpServletResponse httpResponse) throws Exception {
		// 记录支付流程开始，包含订单ID便于追踪
		System.out.println("接收支付请求，订单ID：" + orderId);

		// 校验订单ID非空
		if (orderId == null) {
			System.err.println("支付失败：订单ID不能为空");
			httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, "订单ID不能为空");
			return;
		}

		Order order = null;
		try {
			// 查询订单信息并记录日志
			System.out.println("开始查询订单详情，订单ID：" + orderId);
			order = orderService.getOrderDetail(orderId);

			if (order == null) {
				System.err.println("支付失败：未查询到订单，订单ID：" + orderId);
				throw new FarmException(ResultCodeEnum.FAIL.getCode(), "未查询到订单");
			}
			System.out.println("订单查询成功，订单信息：" +
					"订单号=" + order.getOrderId() +
					", 金额=" + order.getTotalPrice() +
					", 状态=" + order.getStatus());

			// 判断订单状态
			if (order.getStatus() != 0) {
				System.err.println("支付失败：订单状态异常，订单ID：" + orderId + ", 当前状态：" + order.getStatus());
				throw new FarmException(ResultCodeEnum.FAIL.getCode(), "订单状态异常");
			}

			// 创建AlipayClient并记录关键配置（注意脱敏，不打印密钥）
			System.out.println("开始初始化支付宝客户端，APPID：" + aliPayConfig.getAppId().substring(0, 4) + "****");
			AbstractAlipayClient alipayClient = new DefaultAlipayClient(
					GATEWAY_URL,
					aliPayConfig.getAppId(),
					aliPayConfig.getAppPrivateKey(),
					FORMAT,
					CHARSET,
					aliPayConfig.getAlipayPublicKey(),
					SIGN_TYPE
			);

			// 构建支付请求参数
			AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
			request.setNotifyUrl(aliPayConfig.getNotifyUrl());
			System.out.println("设置异步通知地址：" + aliPayConfig.getNotifyUrl());

			JSONObject bizContent = new JSONObject();
			bizContent.put("out_trade_no", order.getOrderId());
			bizContent.put("total_amount", order.getTotalPrice());
			bizContent.put("subject", order.getProductName());
			bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
			request.setBizContent(bizContent.toString());

			// 设置同步回调地址
			request.setReturnUrl("http://localhost:5173/farmProducts");
			System.out.println("设置同步回调地址：" + request.getReturnUrl());
			System.out.println("支付请求参数：" + bizContent.toString());

			// 调用支付宝SDK生成表单
			System.out.println("开始调用支付宝SDK生成支付表单");
			String form = alipayClient.pageExecute(request).getBody();
			System.out.println("支付宝表单生成成功，长度：" + (form != null ? form.length() : 0));

			// 输出表单到前端
			httpResponse.setContentType("text/html;charset=" + CHARSET);
			httpResponse.getWriter().write(form);
			httpResponse.getWriter().flush();
			httpResponse.getWriter().close();


		} catch (AlipayApiException e) {
			e.printStackTrace();
			throw new FarmException(ResultCodeEnum.FAIL.getCode(), "支付接口调用失败");
		} catch (FarmException e) {
			// 业务异常（已在前面打印日志）
			throw e;
		} catch (Exception e) {
			// 其他未知异常
			e.printStackTrace();
			throw new FarmException(ResultCodeEnum.FAIL.getCode(), "支付处理失败");
		}
	}


	@PostMapping("/notify")
	public void payNotify (HttpServletRequest request) throws Exception{
		if (request.getParameter("trade_status").equals("TRADE_SUCCESS")){
			System.out.println("======支付宝异步回调=====");
			Map<String, String> params = new HashMap<>();
			Map<String, String[]> requestParams = request.getParameterMap();
			for (String name : requestParams.keySet()) {
				params.put(name, request.getParameter(name));
			}
			String sign = params.get("sign");
			String content = AlipaySignature.getSignCheckContentV1(params);
			boolean checkSignature = AlipaySignature.rsa256CheckContent(content,sign,
					aliPayConfig.getAlipayPublicKey(),"utf-8");

			System.out.println("异步回调验签：" + checkSignature);
			if (!checkSignature) {
				System.out.println("签名验证失败");
				return;
			}
			if (checkSignature) {
				System.out.println("签名验证成功");

				System.out.println("交易名称：" + params.get("subject"));
				System.out.println("交易状态：" + params.get("trade_status"));
				System.out.println("支付宝交易凭证号：" + params.get("trade_no"));
				System.out.println("商户订单号：" + params.get("out_trade_no"));
				System.out.println("交易金额：" + params.get("total_amount"));
				System.out.println("买家在支付宝唯一 id：" + params.get("buyer_id"));
				System.out.println("买家付款时间：" + params.get("gmt_payment"));
				System.out.println("买家付款金额：" + params.get("buyer_pay_amount"));

				String tradeNo = params.get("out_trade_no"); // 订单编号
				String gmtPayment = params.get("gmt_payment"); // 支付时间
				String alipayTradeNo = params.get("trade_no"); // 支付宝交易编号


				// 更新订单状态
				orderService.updateOrderStatus(tradeNo, gmtPayment, alipayTradeNo);

			}
		}

	}



}